package edu.polsl.bio.str.manager.messaging;

import edu.polsl.bio.str.common.messaging.StrJobPayload;
import edu.polsl.bio.str.manager.constant.Constants;
import edu.polsl.bio.str.manager.logic.JobDispatcherBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.MessageHandler;
import org.springframework.integration.message.MessageHandlingException;
import org.springframework.integration.message.MessageRejectedException;

/**
 * //todo class description
 * <p/>
 * Created on: Jul 14, 2011 12:09:59 AM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class DispatcherMessageHandler implements MessageHandler {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(DispatcherMessageHandler.class.getName());

  private JobDispatcherBean jobDispatcherBean;

  @Override
  public void handleMessage(Message<?> message) throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
    try {
      StrJobPayload jobPayload = (StrJobPayload) message.getPayload();
      String nodeIp = (String) message.getHeaders().get(Constants.NODE_IP_HEADER);
      log.debug("Handling dispatcher payload {} for node {}", jobPayload, nodeIp);

      jobDispatcherBean.dispatchJob(nodeIp, jobPayload);
    } catch (Exception e) {
      log.error("Exception occurred during dispatching job", e);
    }
  }

  public void setJobDispatcherBean(JobDispatcherBean jobDispatcherBean) {
    this.jobDispatcherBean = jobDispatcherBean;
  }
}
